<template>
  <div>
    <el-card class="box-card dizhi_1">
      <div slot="header" class="clearfix">
        <span>收货地址</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text"
          >操作按钮</el-button
        > -->
      </div>
      <div class="text item">
        <div class="dizhi_bianji">
          <div :class="this.type == 0 ? 'bianji_tou ' : 'baocun_tou'">
            {{ this.type == 1 ? "添加" : "编辑" }}收货地址
          </div>

          <el-form
           status-icon
            class="form_dizhi"
            label-width="100px"
            :model="formLabelAlign"
             :rules="rules"
             ref="formLabelAlign"
            
          >
            <el-form-item label="地区信息"  >
              <VDistpicker
                @province="onChangeProvince"
                @city="onChangeCity"
                @area="onChangeArea"
                :province="formLabelAlign.Province"
                :city="formLabelAlign.City"
                :area="formLabelAlign.County"
              >
                </VDistpicker
              >
            </el-form-item>
            <el-form-item label="详细地址" prop="Desc" size="mini">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="formLabelAlign.Desc"
              >
              </el-input>
            </el-form-item>

            <el-form-item label="收货人姓名" prop="name"  size="mini">
              <el-input v-model="formLabelAlign.name"></el-input>
            </el-form-item> 
            <el-form-item label="手机号码" prop="phoneNumber"  size="mini">
              <el-input v-model.number="formLabelAlign.phoneNumber"></el-input>
            </el-form-item>
          </el-form>
          <el-switch v-model="value1" active-text="设置为默认收货地址">
          </el-switch>
        </div>
        <el-button type="primary" size="mini" @click="submitForm('formLabelAlign')" class="baocun"
          >保存</el-button
        >
        <el-button
          type="primary"
          size="mini"
          @click="xiugai_quxiao"
          v-if="this.type == 0"
          >取消修改</el-button
        >
        <div class="dizhi_list">
          <div class="list_tou el-icon-warning-outline" style="color:#8e8e8f">
            已保存{{this.tableData.length}}了条地址，还能保存{{20-this.tableData.length}}条地址
          </div>

          <el-table
            :data="tableData"
            v-loading="loading"
            element-loading-text="拼命加载中"
            :key="tableData.addressId"
            border
             empty-text="您暂时还未添加地址"
            style="width: 100% "
            :header-cell-style="{ background: '#EBECF0', color: '#606266' }"
            ref="table"
            @selection-change="handleSelectionChange"
            :default-sort="{ prop: 'addressDefault', order: 'descending' }"
          >
            <el-table-column type="selection" width="55"> </el-table-column>

            <el-table-column prop="receiveName" label="收货人" width="70">
            </el-table-column>
            <el-table-column label="所在地区" width="115">
              <template slot-scope="scope">
                <div>
                  {{
                    scope.row.receiveProvince +
                      scope.row.receiveCity +
                      scope.row.receiveCounty
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="receiveDesc" label="详细地址" width="200">
            </el-table-column>

            <el-table-column prop="receivePhoneNumber" label="电话" width="140">
            </el-table-column>
            <el-table-column prop="cz" label="操作" width="110">
              <template slot-scope="scope">
                <a @click="handleEdit(scope.$index, scope.row)">编辑</a>
                <span>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;</span>
                <a
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  >删除</a
                >
              </template>
            </el-table-column>
            <el-table-column prop="addressDefault" label="状态" width="110">
              <template slot-scope="scope">
                <a
                  :class="scope.row.addressDefault == 1 ? 'type ' : ''"
                  @click="handleEdit1(scope.$index, scope.row)"
                  >{{
                    scope.row.addressDefault == 1 ? "默认地址" : "设为默认"
                  }}</a
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button
            v-if="this.xz_list.length > 0"
            @click="deletBatch"
            type="primary"
            >批量删除</el-button
          >
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import Nav from "../../com/components/Common/Nav.vue";
import HeadNav from "../../com/components/Common/HeadNav.vue";

import caidan from "../../pages/User/caidan";
import axios from "axios";
import VDistpicker from "v-distpicker";
import Qs from "qs";
// import axios from "axios";
export default {
  components: { Nav, HeadNav, caidan, VDistpicker },

  data() {
    var checkName=(rule, value, callback)=>{
      if(!value){
        return callback(new Error("不能为空"));
      }else{
         callback();
      }
    };
     var checkName1=(rule, value, callback)=>{
      if(!value){
        return callback(new Error("不能为空"));
      }else{
         callback();
      }
    };
   
     var checkNumber = (rule, value, callback) => {
       var regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }
     
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (!regMobile.test(value)) {
            callback(new Error("请输入有效的11位手机号码！"));
          } else {
            
            callback()
          }
        }
     
     }
    return {
      userInfo: "",
      loading: false,

      type: 1, //判断是修改状态还是添加状态  默认添加状态
      formLabelAlign: {
        name: "",
        phoneNumber: "",
        yzbm: "",
        Province: "",
        County: "",
        City: "",
        Desc: "",
        addressId: "",
        index: "",
      },
      value1: false,
      tableData: [],
      xz_list: [],
        rules: {
       
      
       
        phoneNumber: [{ validator: checkNumber, trigger: "blur" }],
        name: [{ validator: checkName, trigger: "blur" }],
        Desc: [{ validator: checkName1, trigger: "blur" }],
     
      },
    };
  },
  methods: {
     submitForm(formLabelAlign) {
      //添加、修改收货地址
       this.$refs[formLabelAlign].validate(async (valid) =>{
         if(valid){
      const address = {};
      this.loading = true; //开始加载动画
      if (this.type == 1) {
        if (this.value1 == 1) {
          for (let item of this.tableData) {
            item.addressDefault = 0;
          }

//post
          for (let item of this.tableData) {
            await axios
              .put(
                "/fl-address/modifyAddressByAddressId",
                {
                  addressDefault: 0,
                  name: item.receiveName,
                  phoneNum: item.receivePhoneNumber,
                  receiveCity: item.receiveCity,
                  receiveCounty: item.receiveCounty,
                  receiveDesc: item.receiveDesc,
                  receiveProvince: item.receiveProvince,
                  userId: item.userId,
                  addressId: item.addressId,
                },
                {
                  headers: {
                    Authorization: localStorage.getItem("token"),
                  },
                }
              )
              .then((res) => {
                ;
              });
          }
        }

        axios
          .post(
            "/fl-address/addAddress",
            {
              addressDefault: this.value1,
              name: this.formLabelAlign.name,
              phoneNum: this.formLabelAlign.phoneNumber,
              receiveCity: this.formLabelAlign.City,
              receiveCounty: this.formLabelAlign.County,
              receiveDesc: this.formLabelAlign.Desc,
              receiveProvince: this.formLabelAlign.Province,
              userId: this.userInfo.userId,
            },
            {
              headers: {
                Authorization: localStorage.getItem("token"),
              },
            }
          )
          .then((res) => {
            ;
            axios
              .get("/fl-address/getAddressByAddressId", {
                params: {
                  addressId: res.data.data,
                },
                headers: {
                  Authorization: localStorage.getItem("token"),
                },
              })
              .then((res) => {
                this.tableData.push(res.data.data);
                if (res.data.code == 200) {
                  this.$message({
                    message: "添加地址成功",
                    type: "success",
                  });
                } else {
                  this.$message.error("添加失败请重试");
                }
              });
          });
      } else {
        //修改收货地址
        if (this.value1 == 1) {
          //判断是否修改了默认地址
          for (let item of this.tableData) {
            item.addressDefault = 0;
          }

          for (let item of this.tableData) {
            await axios
              .put(
                "/fl-address/modifyAddressByAddressId",
                {
                  addressDefault: 0,
                  name: item.receiveName,
                  phoneNum: item.receivePhoneNumber,
                  receiveCity: item.receiveCity,
                  receiveCounty: item.receiveCounty,
                  receiveDesc: item.receiveDesc,
                  receiveProvince: item.receiveProvince,
                  userId: item.userId,
                  addressId: item.addressId,
                },
                {
                  headers: {
                    Authorization: localStorage.getItem("token"),
                  },
                }
              )
              .then((res) => {
                ;
              });
          }
          this.tableData[this.formLabelAlign.index].addressDefault = 1;
          this.$refs.table.sort("addressDefault", "descending");
        }

        axios
          .put(
            "/fl-address/modifyAddressByAddressId",
            {
              addressDefault: this.value1,
              name: this.formLabelAlign.name,
              phoneNum: this.formLabelAlign.phoneNumber,
              receiveCity: this.formLabelAlign.City,
              receiveCounty: this.formLabelAlign.County,
              receiveDesc: this.formLabelAlign.Desc,
              receiveProvince: this.formLabelAlign.Province,
              userId: this.userInfo.userId,
              addressId: this.formLabelAlign.addressId,
            },
            {
              headers: {
                Authorization: localStorage.getItem("token"),
              },
            }
          )
          .then((res) => {
            axios
              .get("/fl-address/getAddressByAddressId", {
                params: {
                  addressId: this.formLabelAlign.addressId,
                },
                headers: {
                  Authorization: localStorage.getItem("token"),
                },
              })
              .then((res) => {
                //  this.tableData.forEach((index,element) => {
                //    if(element.addressId==this. formLabelAlign.addressId){
                //      
                //    }
                //  });
                this.getdizhilist();
              
                if (res.data.code == 200) {
                  this.$message({
                    message: "修改地址成功",
                    type: "success",
                  });
                } else {
                  this.$message.error("修改失败请重试");
                }
                // this.tableData.push(res.data.data)
                ;
              });
          });
      }

      this.loading = false;
      }
      else if(this.formLabelAlign.County==''){
         this.$message.error('地区信息请选择完整');
      }
      // else 
      // {
      //   ;
      //    this.$message.error('地址格式错误，请检查');
      //     return false;
      // }
       });
    },
    xiugai_quxiao() {
      //取消修改
      this.type = 1;
      this.formLabelAlign.name = "";
      this.formLabelAlign.phoneNumber = "";
      this.formLabelAlign.yzbm = 435400;
      this.formLabelAlign.Province = "";
      this.formLabelAlign.City = "";
      this.formLabelAlign.County = "";
      this.formLabelAlign.Desc = "";

      this.value1 = "false";
      this.$message({
        message: "已取消修改",
        type: "success",
      });
    },
    onChangeProvince(a) {
      this.formLabelAlign.Province = a.value;
    },
    onChangeCity(a) {
      this.formLabelAlign.City = a.value;
    },
    onChangeArea(a) {
      this.formLabelAlign.County = a.value;
    },
    handleEdit(index, val) {
      this.formLabelAlign.name = val.receiveName;
      this.formLabelAlign.phoneNumber = Number(val.receivePhoneNumber);
      this.formLabelAlign.yzbm = 435400;
      this.formLabelAlign.Province = val.receiveProvince;
      this.formLabelAlign.City = val.receiveCity;
      this.formLabelAlign.County = val.receiveCounty;
      this.formLabelAlign.Desc = val.receiveDesc;
      this.formLabelAlign.addressId = val.addressId;
      this.type = 0;
      this.formLabelAlign.index = index;
      if (val.addressDefault == 1) this.value1 = true;
      else this.value1 = false;
      ;
    },
    formatter(row, column) {
      return row.address;
    },
    async handleEdit1(index, val) {
      this.loading = true;
      //设置默认地址使其排在地址列表第一个
      for (let item of this.tableData) {
        item.addressDefault = 0;
      }
      ;
      for (let item of this.tableData) {
        await axios
          .put(
            "/fl-address/modifyAddressByAddressId",
            {
              addressDefault: 0,
              name: item.receiveName,
              phoneNum: item.receivePhoneNumber,
              receiveCity: item.receiveCity,
              receiveCounty: item.receiveCounty,
              receiveDesc: item.receiveDesc,
              receiveProvince: item.receiveProvince,
              userId: item.userId,
              addressId: item.addressId,
            },
            {
              headers: {
                Authorization: localStorage.getItem("token"),
              },
            }
          )
          .then((res) => {
            ;
          });
      }

      var number = "1";
      ;
      var number1 = Number(number);
      ;
      axios
        .put(
          "/fl-address/modifyAddressByAddressId",
          {
            addressDefault: number1,
            name: val.receiveName,
            phoneNum: val.receivePhoneNumber,
            receiveCity: val.receiveCity,
            receiveCounty: val.receiveCounty,
            receiveDesc: val.receiveDesc,
            receiveProvince: val.receiveProvince,
            userId: val.userId,
            addressId: val.addressId,
          },
          {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          }
        )
        .then((res) => {
          ;
          val.addressDefault = 1;
          this.$refs.table.sort("addressDefault", "descending");
          this.loading = false;
        });
    },
    getdizhilist() {
      //获取用户收货地址
      this.loading = true;
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      axios
        .get("/fl-address/getAddressByUserId", {
          params: {
            userId: this.userInfo.userId,
          },
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          this.tableData = res.data.data;
          ;
          this.loading = false;
        });
    },
    handleDelete(index, val) {
      //单点删除

      ;
      this.$confirm("是否从购物车中移除该商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          var params = new URLSearchParams();
          ;
          params.append("addressIds", val.addressId);
          axios
            .delete(
              "/fl-address/deleteAddressByAddressIds",
              {
                params,
                headers: {
                  Authorization: localStorage.getItem("token"),
                },
              }
            )
            .then((res) => {
              ;
             this.getdizhilist();
              this.loading = false;
              if (res.data.code == 200) {
                this.$message({
                  type: "success",

                  message: res.data.msg,
                });
              }else{
                 this.$message.error('删除失败请重试');
              }
            });
        })
        .catch(() => {
          this.loading = false;
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(val) {
      //保存勾选的地址
      ;
      this.xz_list = val;
    },
    deletBatch() {
      const arr = [];
      this.xz_list.forEach((element) => {
        arr.push(element.addressId);
      });

      this.$confirm("是否从购物车中移除当前选中的商品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var params = new URLSearchParams();

          params.append("addressIds", arr);
          axios
            .delete(
              "/fl-address/deleteAddressByAddressIds",
              {
                params,
                headers: {
                  Authorization: localStorage.getItem("token"),
                },
              }
            )
            .then((res) => {
              this.xz_list.forEach((i) => {
                //批量删除后重新筛选数组渲染页面

                this.tableData.splice(
                  this.tableData.findIndex((j) => j.addressId === i.addressId),
                  1
                );
              });
              this.$message({
                type: "success",
                message: res.data.msg,
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.getdizhilist();
  },
};
</script>

<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.dizhi_1 {
  width: 960px;
}

.dizhi_bianji {
  position: relative;
  .bianji_tou {
    width: 100%;
    height: 30px;
    line-height: 30px;
    background: #409eff;
    margin-bottom: 20px;
  }
  .baocun_tou {
    width: 100%;
    height: 30px;
    line-height: 30px;
    background: #f3f8fe;
    margin-bottom: 20px;
  }

  .form_dizhi {
    width: 450px;
    margin-bottom: 5px;
  }
  .dizhi_xz {
    height: 10px;
  }
}
.item {
  .baocun {
    margin-top: 10px;
    margin-left: 25%;
    margin-bottom: 20px;
  }
}
.dizhi_list {
  .list_tou {
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: #f3f8fe;
    margin-bottom: 20px;
  }
  a {
    color: rgb(65, 65, 65);
    cursor: pointer;
  }
  .type {
    border: 1px #ff5000 solid;
    border-radius: 10px;
    color: #ff3300;
    font-size: 10px;
    background: #ffd6cc;
  }
}
</style>
